<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>医生管理</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <link th:href="@{/css/admin.css}" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body>
<div class="content-section" th:fragment="content">
    <h2><i class="fas fa-user-md"></i> 医生管理</h2>
    
    <div class="filter-section">
        <select id="deptSelect" class="dept-select">
            <option value="">所有科室</option>
        </select>
    </div>
    
    <div class="action-bar">
        <button class="btn btn-primary" onclick="showAddDoctorModal()">
            <i class="fas fa-plus"></i> 添加医生
        </button>
    </div>
    
    <div th:fragment="doctorList">
        <table class="data-table">
            <thead>
                <tr>
                    <th>科室</th>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th>电话号码</th>
                    <th>身份证号</th>
                </tr>
            </thead>
            <tbody id="doctorTableBody">
            </tbody>
        </table>
    </div>
    
    <div id="addDoctorModal" class="modal" style="display: none;">
        <div class="modal-content">
            <h3>添加新医生</h3>
            <form id="addDoctorForm">
                <div class="form-group">
                    <label for="doctorId">医生ID</label>
                    <input type="text" id="doctorId" name="doctorId" required>
                </div>
                
                <div class="form-group">
                    <label for="doctorName">姓名</label>
                    <input type="text" id="doctorName" name="doctorName" required>
                </div>
                
                <div class="form-group">
                    <label>性别</label>
                    <div class="radio-group">
                        <label>
                            <input type="radio" name="doctorGender" value="男" checked> 男
                        </label>
                        <label>
                            <input type="radio" name="doctorGender" value="女"> 女
                        </label>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="doctorAge">年龄</label>
                    <input type="number" id="doctorAge" name="doctorAge" min="0" required>
                </div>
                
                <div class="form-group">
                    <label for="doctorIdCard">身份证号</label>
                    <input type="text" id="doctorIdCard" name="doctorIdCard" required>
                </div>
                
                <div class="form-group">
                    <label for="doctorPhone">电话号码</label>
                    <input type="tel" id="doctorPhone" name="doctorPhone" required>
                </div>
                
                <div class="form-group">
                    <label for="deptIdSelect">所属科室</label>
                    <select id="deptIdSelect" name="deptId" required>
                        <option value="">请选择科室</option>
                    </select>
                </div>
                
                <div class="form-buttons">
                    <button type="submit" class="btn btn-primary">保存</button>
                    <button type="button" class="btn btn-secondary" onclick="hideAddDoctorModal()">取消</button>
                </div>
            </form>
        </div>
    </div>

    <script th:inline="javascript">
    /*<![CDATA[*/
    // 在页面加载完成后初始化
    $(document).ready(function() {
        console.log('Document ready, initializing...');
        initializeDoctorManage();
    });
    
    // 页面初始化
    function initializeDoctorManage() {
        console.log('Initializing doctor management page...');
        loadDepartments();
        loadDoctors();
        
        // 绑定事件
        $('#deptSelect').on('change', function() {
            var selectedDeptId = $(this).val();
            console.log('Selected department ID:', selectedDeptId);
            loadDoctors(selectedDeptId);
        });
        
        $('#addDoctorForm').on('submit', function(e) {
            e.preventDefault();
            addDoctorForm();
        });
    }

    // 加载科室列表
    function loadDepartments() {
        console.log('Starting to load departments...');
        var url = /*[[@{/admin/departments}]]*/ '/admin/departments';
        console.log('Departments URL:', url);
        
        $.ajax({
            url: url,
            method: 'GET',
            dataType: 'json',
            success: function(departments) {
                console.log('Received departments:', departments);
                
                var deptSelect = $('#deptSelect');
                var deptIdSelect = $('#deptIdSelect');
                
                // 清空现有选项（保留第一个默认选项）
                deptSelect.find('option:not(:first)').remove();
                deptIdSelect.find('option:not(:first)').remove();
                
                // 添加科室选项到两个下拉列表
                departments.forEach(function(dept) {
                    if (!dept || !dept.deptId || !dept.deptName) {
                        console.warn('Invalid department data:', dept);
                        return;
                    }
                    
                    // 添加到筛选下拉列表
                    deptSelect.append($('<option>', {
                        value: dept.deptId,
                        text: dept.deptName
                    }));
                    
                    // 添加到添加医生表单的下拉列表
                    deptIdSelect.append($('<option>', {
                        value: dept.deptId,
                        text: dept.deptName
                    }));
                });
                
                console.log('Updated department select lists');
            },
            error: function(xhr, status, error) {
                console.error('Failed to load departments:', {
                    status: status,
                    error: error,
                    response: xhr.responseText,
                    statusCode: xhr.status
                });
                if (xhr.status === 401) {
                    window.location.href = /*[[@{/admin/auth/login}]]*/ '/admin/auth/login';
                } else {
                    alert('加载科室列表失败，请刷新页面重试\n错误信息：' + error);
                }
            }
        });
    }

    // 加载医生信息
    function loadDoctors(deptId) {
        console.log('Loading doctors with deptId:', deptId);
        var url = /*[[@{/admin/doctors}]]*/ '/admin/doctors';
        if (deptId) {
            url += '?deptId=' + deptId;
        }
        console.log('Doctors URL:', url);
        
        $.ajax({
            url: url,
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                console.log('Received doctors response:', response);
                var tbody = $('#doctorTableBody');
                tbody.empty();
                
                if (!Array.isArray(response)) {
                    console.error('Invalid doctors data:', response);
                    tbody.append('<tr><td colspan="6" class="text-center">获取医生数据格式不正确</td></tr>');
                    return;
                }
                
                if (response.length === 0) {
                    tbody.append('<tr><td colspan="6" class="text-center">暂无医生数据</td></tr>');
                    return;
                }
                
                response.forEach(function(doctor) {
                    console.log('Processing doctor:', doctor);
                    var row = $('<tr>');
                    row.append($('<td>').text(doctor.deptName || '-'));
                    row.append($('<td>').text(doctor.doctorName || '-'));
                    row.append($('<td>').text(doctor.doctorAge || '-'));
                    row.append($('<td>').text(doctor.doctorGender || '-'));
                    row.append($('<td>').text(doctor.doctorPhone || '-'));
                    row.append($('<td>').text(doctor.doctorIdCard || '-'));
                    tbody.append(row);
                });
            },
            error: function(xhr, status, error) {
                console.error('Failed to load doctors:', {
                    status: status,
                    error: error,
                    response: xhr.responseText,
                    statusCode: xhr.status
                });
                var tbody = $('#doctorTableBody');
                tbody.empty();
                
                if (xhr.status === 401) {
                    window.location.href = /*[[@{/admin/auth/login}]]*/ '';
                } else {
                    tbody.append('<tr><td colspan="6" class="text-center text-danger">加载医生列表失败，请刷新页面重试<br>错误信息：' + error + '</td></tr>');
                }
            }
        });
    }

    function showAddDoctorModal() {
        $('#addDoctorModal').show();
        loadDepartmentsForSelect();
    }

    function hideAddDoctorModal() {
        $('#addDoctorModal').hide();
        $('#addDoctorForm')[0].reset();
    }

    function loadDepartmentsForSelect() {
        console.log('Loading departments for select...');
        $.ajax({
            url: /*[[@{/admin/departments}]]*/ '/admin/departments',
            method: 'GET',
            dataType: 'json',
            contentType: 'application/json',
            success: function(response) {
                console.log('Received departments for select:', response);
                var select = $('#deptIdSelect');
                select.find('option:not(:first)').remove();
                
                if (!Array.isArray(response)) {
                    console.error('Invalid departments data for select:', response);
                    alert('获取科室列表失败');
                    return;
                }
                
                response.forEach(function(dept) {
                    select.append($('<option>', {
                        value: dept.deptId,
                        text: dept.deptName
                    }));
                });
            },
            error: function(xhr, status, error) {
                console.error('Failed to load departments for select:', {
                    status: status,
                    error: error,
                    response: xhr.responseText,
                    statusCode: xhr.status,
                    headers: xhr.getAllResponseHeaders()
                });
                if (xhr.status === 401) {
                    window.location.href = /*[[@{/admin/auth/login}]]*/ '';
                } else {
                    alert('加载科室列表失败');
                }
            }
        });
    }

    // 处理表单提交
    function addDoctorForm() {
        // 获取表单数据
        var formData = {
            doctorId: $('#doctorId').val(),
            doctorName: $('#doctorName').val(),
            doctorGender: $('input[name="doctorGender"]:checked').val(),
            doctorAge: parseInt($('#doctorAge').val()),
            doctorIdCard: $('#doctorIdCard').val(),
            doctorPhone: $('#doctorPhone').val(),
            deptId: parseInt($('#deptIdSelect').val())
        };

        // 表单验证
        var errors = [];
        
        // 验证医生ID
        if (!formData.doctorId) {
            errors.push('医生ID不能为空');
        } else if (!/^[A-Za-z][A-Za-z0-9]*$/.test(formData.doctorId)) {
            errors.push('医生ID必须以字母开头，且只能包含字母和数字');
        }
        
        // 验证姓名
        if (!formData.doctorName) {
            errors.push('医生姓名不能为空');
        } else if (formData.doctorName.length > 50) {
            errors.push('医生姓名长度不能超过50个字符');
        }
        
        // 验证性别
        if (!formData.doctorGender) {
            errors.push('请选择性别');
        }
        
        // 验证年龄
        if (!formData.doctorAge) {
            errors.push('年龄不能为空');
        } else if (formData.doctorAge < 18 || formData.doctorAge > 100) {
            errors.push('年龄必须在18-100岁之间');
        }
        
        // 验证身份证号
        if (!formData.doctorIdCard) {
            errors.push('身份证号不能为空');
        } else if (!/^\d{17}[\dX]$/.test(formData.doctorIdCard)) {
            errors.push('请输入正确的18位身份证号');
        }
        
        // 验证电话号码
        if (!formData.doctorPhone) {
            errors.push('电话号码不能为空');
        } else if (!/^\d{11}$/.test(formData.doctorPhone)) {
            errors.push('请输入正确的11位手机号码');
        }
        
        // 验证科室
        if (!formData.deptId) {
            errors.push('请选择科室');
        }
        
        // 如果有错误，显示错误信息并返回
        if (errors.length > 0) {
            alert(errors.join('\n'));
            return;
        }

        // 发送请求
        $.ajax({
            url: /*[[@{/admin/addDoctor}]]*/ '',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(response) {
                if (response.success) {
                    alert('添加成功，医生ID：' + response.doctorId + '\n初始密码为身份证后6位');
                    hideAddDoctorModal();
                    loadDoctors(); // 刷新医生列表
                } else {
                    alert(response.message || '添加失败');
                }
            },
            error: function(xhr, status, error) {
                console.error('Failed to add doctor:', xhr.responseText);
                var errorMessage = '添加失败';
                
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response.message) {
                        errorMessage = response.message;
                    }
                } catch(e) {
                    // 处理特定的错误信息
                    if (xhr.responseText.includes('doctorIdCard')) {
                        errorMessage = '该身份证号已被注册';
                    } else if (xhr.responseText.includes('doctorPhone')) {
                        errorMessage = '该电话号码已被注册';
                    } else if (xhr.responseText.includes('doctorId')) {
                        errorMessage = '该医生ID已存在';
                    }
                }
                
                alert(errorMessage);
            }
        });
    }
    /*]]>*/
    </script>

    <style th:fragment="style">
    /* 表格样式 */
    .data-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
    }

    .data-table th,
    .data-table td {
        padding: 12px;
        text-align: left;
        border-bottom: 1px solid #e0e0e0;
    }

    .data-table th {
        background-color: #f5f5f5;
        font-weight: 600;
    }

    .data-table tr:hover {
        background-color: #f8f9fa;
    }

    /* 过滤器样式 */
    .filter-section {
        margin-bottom: 20px;
    }

    .dept-select {
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
        min-width: 200px;
    }

    /* 按钮样式 */
    .action-bar {
        margin-bottom: 20px;
    }

    .btn {
        padding: 8px 16px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
    }

    .btn-primary {
        background-color: #4CAF50;
        color: white;
    }

    .btn-primary:hover {
        background-color: #45a049;
    }

    .btn-secondary {
        background-color: #f44336;
        color: white;
    }

    .btn-secondary:hover {
        background-color: #d32f2f;
    }

    /* 模态框样式 */
    .modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
    }

    .modal-content {
        background-color: white;
        padding: 20px;
        border-radius: 8px;
        width: 90%;
        max-width: 500px;
    }

    .modal-content h3 {
        margin-top: 0;
        margin-bottom: 20px;
    }

    /* 表单样式 */
    .form-group {
        margin-bottom: 15px;
    }

    .form-group label {
        display: block;
        margin-bottom: 5px;
        font-weight: 500;
    }

    .form-group input,
    .form-group select {
        width: 100%;
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
    }

    .radio-group {
        display: flex;
        gap: 20px;
    }

    .radio-group label {
        display: flex;
        align-items: center;
        gap: 5px;
        cursor: pointer;
    }

    .form-buttons {
        margin-top: 20px;
        display: flex;
        gap: 10px;
        justify-content: flex-end;
    }
    </style>
</div>
</body>
</html> 